package com.yrd.fssync.core;

import java.util.Comparator;
import java.util.HashMap;
import java.util.PriorityQueue;

public class KeyList {
	HashMap<String, SyncRequestWrap> map;
	PriorityQueue<SyncRequestWrap> queue;
	
	
	class SyncRequestWrap{
		public SyncRequest syncRequest;
		public SyncRequestWrap(SyncRequest syncRequest) {
			this.syncRequest = syncRequest;
		}
	}
		
	public KeyList() {
		this.map = new HashMap<String, SyncRequestWrap>();
		this.queue = new PriorityQueue<SyncRequestWrap>(512,new Comparator<SyncRequestWrap>(){
			public int compare(SyncRequestWrap o1, SyncRequestWrap o2) {
				return (int)(o1.syncRequest.timestamp - o2.syncRequest.timestamp);
			}
	    });
	}
	
	public synchronized void add(SyncRequest syncRequest){
		SyncRequestWrap syncRequestWrap = map.get(syncRequest.getLocalFile().getAbsolutePath());
		if(syncRequestWrap==null){
			syncRequestWrap = new SyncRequestWrap(syncRequest);
			map.put(syncRequest.getLocalFile().getAbsolutePath(), syncRequestWrap);
			queue.add(syncRequestWrap);
		}else if(syncRequestWrap.syncRequest.timestamp < syncRequest.timestamp){
			queue.remove(syncRequestWrap);
			syncRequestWrap.syncRequest = syncRequest;
			queue.add(syncRequestWrap);
		}
	}
	
	public synchronized SyncRequest poll(){
		SyncRequestWrap syncRequestWrap  = queue.poll();
		if(syncRequestWrap!=null){
			map.remove(syncRequestWrap.syncRequest.getLocalFile().getAbsolutePath());
			return syncRequestWrap.syncRequest;
		}else{
			return null;
		}
	}
	
	public synchronized boolean isEmpty(){
		return queue.isEmpty();
	}
	
	public synchronized int size(){
		return queue.size();
	}
}
